<?php

namespace app\admin\controller\xilumarket\appeal;

use app\admin\model\xilumarket\order\Order;
use app\admin\model\xilumarket\order\OrderProduct;
use app\admin\model\xilumarket\user\User;
use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Hook;
use think\response\Json;

/**
 * 订单申诉
 *
 * @icon fa fa-circle-o
 */
class Appeal extends Backend
{

    protected $relationSearch = true;
    /**
     * OrderAppeal模型对象
     * @var \app\admin\model\xilumarket\appeal\OrderAppeal
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\xilumarket\appeal\OrderAppeal;
        $this->view->assign("stateList", $this->model->getStateList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with(['user'=>function($q){
                $q->withField(['id','nickname','avatar']);
            }
            ])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }



    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $send_user_id = $row->user_id;
            $receive_user_id = Order::where('id',$row->order_id)->value('seller_user_id');
            $product_id = OrderProduct::where('id',$row->order_product_id)->value('product_id');
            $session = \app\common\model\xilumarket\ChatSession::where(function ($query) use ($send_user_id, $receive_user_id) {
                $query->where('send_user_id', $send_user_id)->where('receive_user_id', $receive_user_id)
                    ->whereOr(function ($query) use ($send_user_id, $receive_user_id) {
                        $query->where('send_user_id', $receive_user_id)->where('receive_user_id', $send_user_id);
                    });
            })
                ->where('product_id',$product_id)
                ->find();
            $chat_lists = $session?\app\common\model\xilumarket\Chat::where('session_id',$session->id)->select():[];
            //halt(collection($chat_lists)->toArray());
            $myuserinfo = User::field("id,nickname,avatar")->where('id',$send_user_id)->find();
            $touserinfo = User::field("id,nickname,avatar")->where('id',$receive_user_id)->find();

            $this->view->assign('chat_lists', $chat_lists);
            $this->view->assign('myuserinfo', $myuserinfo);
            $this->view->assign('touserinfo', $touserinfo);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if($row['state'] == 2){
            $this->error(__('申诉不可操作', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            if($row->state == '2'){
                $params['order_no'] = 'AP'.date('YmdHis').mt_rand(0,9999);
            }
            $result = $row->allowField(true)->save($params);
            //审核通过之后，给用户退款，佣金作废
            if($row->state == '2'){
                Hook::listen("xilumarket_appeal_success",$row);
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }



}
